2

redis.js

var ioRedis = require('ioredis');
var logger = require('./logger');
var redis = new ioRedis();
// 默认127.0.0.1:6379
// redis 链接错误
redis.on("error", function (error) {
    logger.error(error);
});
exports.redis = redis;

app.js

const index = require('./routes/index.js');
const app = express();
const cookieParser = require('cookie-parser')
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const http = require('http');
const httpServer = http.createServer(app);
var redis = require('./redis/redis.js').reids;
...其他中间件省略
app.use(cookieParser('sessiontest'));
app.use(session({
  store: new RedisStore({
    client: redis,
    prefix: 'hgk'
  }),
  cookie: { maxAge: 1 * 60 * 60 * 1000 }, //默认1小时
  secret: 'sessiontest',
  resave: true,
  saveUninitialized: true
}));
app.use('/', index)
//全局error中间件
app.use(function(err, req, res, next) {
  console.log("Error happens", err.stack);
});
httpServer.listen(3000, function() {
  console.log('HTTP Server is running on: http://localhost:%s', 3000);
});

第一次登陆

router.get('/login', function(req, res, next) {
    // 从数据库中比对账号验证是否成功,如成功保存用户信息
    var user={
        name:"Chen-xy",
        age:"22",
        address:"bj"
    }
  req.session.user=user;
  res.json('登陆成功')
});

需要登陆验证的路由

//获取文章
router.get('/articals', function(req, res, next) {
    if(req.session.user){
        var user=req.session.user;
        var name=user.name;
        res.send('你好'+name+',欢迎来到我的家园。');
    }else{
        res.send('你还没有登录,先登录下再试试!');
    }
});

个人项目小博客链接https://github.com/hangaoke1/...

参考文章:
http://blog.csdn.net/u0126795...
http://wiki.jikexueyuan.com/p...
http://blog.csdn.net/yuanguoz...


小脑fu
237 声望9 粉丝